import { registeOnDestoryHook } from '@core/types'
import { expressFactory } from './expressFactory'
import { createLogger } from '@nodejs/logger'
import cluster from 'cluster'
import { ensureDir, readFile, writeFile } from 'fs-extra'
import { homedir } from 'os'
import { join } from 'path'
import { v4 } from 'uuid'

export async function master(index: number = 2) {
    if (cluster.isPrimary && false) {
        for (let i = 0; i < index; i++) {
            cluster.fork({ INDEX: i })
        }
        cluster.on('exit', (worker, code, signal) => {
            console.log(`Worker ${worker.process.pid} died with code: ${code}, and signal: ${signal}`);
            console.log('Starting a new worker');
            cluster.fork();
        });
    } else {
        registeOnDestoryHook()
        const logger = await createLogger('main')
        const home = homedir()
        const jsonFile = `${process.env.INDEX || 0}.json`
        await ensureDir(join(home, 'sker/master'))
        const configPath = join(home, 'sker/master', jsonFile)
        const config = await readJson(configPath)
        const uuid = config.uuid || v4()
        await saveJson(configPath, { uuid })
        const app = await expressFactory(uuid, true)
        const closer = await app.listen()
        logger.info(`Server started on port ${process.env.PORT || 3000}`)
        process.on('exit', async () => {
            await closer()
        })
    }
}

async function readJson(path: string) {
    try {
        const content = await readFile(path, { encoding: 'utf8' })
        const str = content.toString()
        return JSON.parse(str)
    } catch (e) {
        return {}
    }
}

async function saveJson(path: string, value: any) {
    try {
        await writeFile(path, JSON.stringify(value), { encoding: 'utf8' })
    } catch (e) {
        return {}
    }
}